package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.AdminClass;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.domain.UserClass;
import com.ruoyi.system.service.IAdminClassService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IUserClassService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.framework.util.ShiroUtils;

/**
 * 班级Controller
 * 
 * @author ruoyi
 * @date 2020-06-09
 */
@Controller
@RequestMapping("/system/class")
public class AdminClassController extends BaseController
{
    private String prefix = "system/class";

    @Autowired
    private IAdminClassService adminClassService;
    
    @Autowired
    private IUserClassService userClassService;
    
    @Autowired
    private ISysUserService sysUserService;

    @RequiresPermissions("system:class:view")
    @GetMapping()
    public String adminClass()
    {
        return prefix + "/class";
    }

    /**
     * 查询班级列表
     */
    @RequiresPermissions("system:class:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AdminClass adminClass)
    {
        startPage();
        List<AdminClass> list = adminClassService.selectAdminClassList(adminClass);
        
        
        for(AdminClass sysClass:list){
        	List<String> teacherNames=new ArrayList<String>();
        	UserClass userClass=new UserClass();
        	userClass.setClassId(sysClass.getClassId());
        	List<UserClass> userIdList=userClassService.selectUserClassList(userClass);
        	for(UserClass cls:userIdList){
        		SysUser sysUser=sysUserService.selectUserById(cls.getUserId());
        		if(null != sysUser){
        			teacherNames.add(sysUser.getUserName());
        		}
        	}
        	sysClass.setTeacherNames(teacherNames);
        }
        
        return getDataTable(list);
    }

    /**
     * 导出班级列表
     */
    @RequiresPermissions("system:class:export")
    @Log(title = "班级", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AdminClass adminClass)
    {
        List<AdminClass> list = adminClassService.selectAdminClassList(adminClass);
        ExcelUtil<AdminClass> util = new ExcelUtil<AdminClass>(AdminClass.class);
        return util.exportExcel(list, "class");
    }

    /**
     * 新增班级
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
    	//查询当前机构下所有的教师
    	SysUser sysUser=new SysUser();
    	sysUser.setCompanyId(ShiroUtils.getCompanyId());
    	sysUser.setUserType(UserConstants.TEACHER_USER_TYPE);
    	List<SysUser> teacherList=sysUserService.selectSysUserList(sysUser);
    	mmap.put("teacherList", teacherList);
        return prefix + "/add";
    }

    /**
     * 新增保存班级
     */
    @RequiresPermissions("system:class:add")
    @Log(title = "班级", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AdminClass adminClass)
    {
    	adminClass.setCompanyId(ShiroUtils.getSysUser().getUserId());
    	adminClass.setCompanyName(ShiroUtils.getSysUser().getUserName());
    	int num=adminClassService.insertAdminClass(adminClass);
    	
    	if (StringUtils.isNotNull(adminClass.getTeacherIds()))
        {
          // 新增班级教师关系
          List<UserClass> list = new ArrayList<UserClass>();
          for (Long userId : adminClass.getTeacherIds())
          {
            UserClass uc = new UserClass();
            uc.setUserId(userId);
            uc.setClassId(adminClass.getClassId());
            list.add(uc);
          }
          userClassService.deleteUserClassByClassId(adminClass.getClassId());
          userClassService.batchUserClass(list);
        }
        return toAjax(num);
    }

    /**
     * 修改班级
     */
    @GetMapping("/edit/{classId}")
    public String edit(@PathVariable("classId") Long classId, ModelMap mmap)
    {
    	//查询当前机构下所有的教师
    	SysUser sysUser=new SysUser();
    	sysUser.setCompanyId(ShiroUtils.getSysUser().getCompanyId());
    	sysUser.setUserType(UserConstants.TEACHER_USER_TYPE);
    	List<SysUser> teacherList=sysUserService.selectSysUserList(sysUser);
    	mmap.put("teacherList", teacherList);
    	
    	//查询班级信息
        AdminClass adminClass = adminClassService.selectAdminClassById(classId);
        mmap.put("adminClass", adminClass);
        
        //查询班级底下已绑定的教师
        UserClass userClass=new UserClass();
        userClass.setClassId(classId);
        List<UserClass> classList=userClassService.selectUserClassList(userClass);
        //TODU
        List<Long> teacherIdList=new ArrayList<Long>();
        for(UserClass cls:classList){
        	teacherIdList.add(cls.getUserId());
        }
        
        mmap.put("teacherIdList", teacherIdList);
        return prefix + "/edit";
    }

    /**
     * 修改保存班级
     */
    @RequiresPermissions("system:class:edit")
    @Log(title = "班级", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AdminClass adminClass)
    {
    	//修改班级信息
    	int num=adminClassService.updateAdminClass(adminClass);
    	//修改班级教师关系
    	if (StringUtils.isNotNull(adminClass.getTeacherIds()))
        {
          // 新增班级教师关系
          List<UserClass> list = new ArrayList<UserClass>();
          for (Long userId : adminClass.getTeacherIds())
          {
            UserClass uc = new UserClass();
            uc.setUserId(userId);
            uc.setClassId(adminClass.getClassId());
            list.add(uc);
          }
          userClassService.deleteUserClassByClassId(adminClass.getClassId());
          userClassService.batchUserClass(list);
        }
    	
        return toAjax(num);
    }

    /**
     * 删除班级
     */
    @RequiresPermissions("system:class:remove")
    @Log(title = "班级", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
    	int num=adminClassService.deleteAdminClassByIds(ids);
    	String [] classIds=ids.split(",");
    	for(String clsId:classIds){
    		userClassService.deleteUserClassByClassId(Long.parseLong(clsId));
    	}
        return toAjax(num);
    }
    
    /**
     * 班级状态修改
     */
    @Log(title = "班级管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:class:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(AdminClass adminClass)
    {
        return toAjax(adminClassService.changeStatus(adminClass));
    }
    
    /**
     * 跳转学生列表
     */
    @RequiresPermissions("system:class:list")
    @GetMapping("/detail/{classId}")
    public String detail(@PathVariable("classId") Long classId, ModelMap mmap)
    {	
    	mmap.put("classId", classId);
        return "system/student/student";
    }
}
